package com.triptogether.chat.fragments;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.triptogether.R;
import com.triptogether.baseclasses.BaseFragment;
import com.triptogether.chat.adapters.MessagesListAdapter;
import com.triptogether.receivers.DBObjectCreatedReceiver.DBObjectCreatedListener;
import com.triptogether.receivers.MessageCreatedReceiver;
import com.triptogether.services.ChatMessagesService;
import com.triptogether.utils.db.DBManager;
import com.triptogether.utils.db.models.Message;
import com.triptogether.utils.db.models.User;
import com.triptogether.utils.facebook.FacebookSharedPreferences;

public class ChatFragment extends BaseFragment implements DBObjectCreatedListener {

	public static final String ARG_USER_ID = "ARG_USER_ID";

	private ListView chatView;
	private EditText messageEditText;
	private Button sendMessageButton;
	private User userChatWith;
	private MessagesListAdapter messagesListAdapter;
	private MessageCreatedReceiver messageCreatedReceiver;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_chat, container, false);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    // Create the MessageCreatedBroadcastReceiver instance
	    messageCreatedReceiver = new MessageCreatedReceiver(this);
	}

	@Override
	public void onStart() {
		super.onStart();
		
		// Get the activity that contains this fragment and the View that is the root of this fragment
		Activity currentActivity = getActivity();
		View rootView = getView();

		// Find the views in the fragment
		chatView = (ListView) rootView.findViewById(R.id.listview_chat);
		messageEditText = (EditText) rootView.findViewById(R.id.edittext_chat_message);
		sendMessageButton = (Button) rootView.findViewById(R.id.button_send_message);

		// Get the userId from the intent and get the user Object from the local DB
		String otherFacebookUserId = getArguments().getString(ARG_USER_ID);
		userChatWith = DBManager.getInstance(currentActivity).findUserByFacebookId(otherFacebookUserId);

		// Get the messagesList adapter and set it to the chat ListView
		messagesListAdapter = new MessagesListAdapter(currentActivity, userChatWith);
		chatView.setAdapter(messagesListAdapter);

		// Init the views in the fragment
		sendMessageButton.setOnClickListener(sendMessage);
		messageEditText.addTextChangedListener(messageTextWathcer);
	}
	
	@Override
	public void onResume() {
	    super.onResume();
	    
	    // Register the broadcast receiver that indicates that the db changed
	    getActivity().registerReceiver(messageCreatedReceiver, new IntentFilter(MessageCreatedReceiver.INTENT_FILTER_ACTION_MESSAGE_CREATED));
	}
	
	@Override
	public void onPause() {
		super.onPause();

		// Unregister the current DrawerLayout from the TripCreatedBroadcastReceiver
		messageCreatedReceiver.unregisterToDbObjectCreatedReceiverListener(this);

	    // Unregister the broadcast receiver that indicates that the db changed 
	    getActivity().unregisterReceiver(messageCreatedReceiver);
	}
	
	/**
	 * Send a chat message with a WebService.
	 * @param messageText The message to send
	 * @return The message that was sent, and created in the DB.
	 */
	private void sendChatMessage(final String messageText) {		
		// Create the intent for starting the service that will send the messages
		Intent messageServiceIntent = new Intent(getActivity(), ChatMessagesService.class);
		
		// Init the details to send with the intent to the service
		String fromUserFacebookId = FacebookSharedPreferences.getUserFacebookId(getActivity());
		String toUserFacebookId = userChatWith.getFacebookId();
		
		// Put the details as extra in the intent
		messageServiceIntent.putExtra(ChatMessagesService.EXTRA_COMMAND, ChatMessagesService.EXTRA_COMMAND_SEND_MESSAGE);
		messageServiceIntent.putExtra(ChatMessagesService.EXTRA_FROM_USER_FACEBOOK_ID, fromUserFacebookId);
		messageServiceIntent.putExtra(ChatMessagesService.EXTRA_TO_USER_FACEBOOK_ID, toUserFacebookId);
		messageServiceIntent.putExtra(ChatMessagesService.EXTRA_MESSAGE_TEXT, messageText);
		
		// Start the service to send the messages
		getActivity().startService(messageServiceIntent);
	}
	
	/**
	 * {@link OnClickListener} of the sendMessage Button
	 */
	OnClickListener sendMessage = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String message = messageEditText.getText().toString();
			sendChatMessage(message);
			
			// Handle UI
			messageEditText.setText("");
			v.setEnabled(false);
		}
	};
	
	/**
	 * {@link TextWatcher} for the {@link EditText} of the message
	 */
	TextWatcher messageTextWathcer = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			int messageLength = s.toString().trim().length();
			if(messageLength > 0) {
				sendMessageButton.setEnabled(true);
			} else {
				sendMessageButton.setEnabled(false);
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
		
		@Override
		public void afterTextChanged(Editable s) {}
	};

	@Override
    public void onObjectCreated(Object dbObject) {
		// We registered to the MessageCreatedBroadcastReceiver, so we suppose to get message object
		Message message = (Message) dbObject;
		
		// Add the message to the messagesListAdapter
		messagesListAdapter.add(message);	    
    }
	
}
